//
//  KFDClient.m
//  KFD
//
//  Created by JIRENTIANXIANG on 6/5/15.
//  Copyright (c) 2015 KFD. All rights reserved.
//

#import "client_config.h"
#import "KFDClient.h"
#import "NSMutableURLRequest+convenience.h"
#import "NSMutableDictionary+checkForNil.h"
#import "KFDResponseBody.h"
#import "NSString+encryption.h"
#import "NSURLSessionTask+custom.h"
#import "KFDAccountManager.h"
#import "KFDEncryptor.h"
#import "KFDStringConcatenator.h"
#import "NSURL+convenience.h"
#import "NSMutableURLRequest+convenience.h"
#import "NSString+URLEncoding.h"
#import "NSDate+format.h"

@implementation KFDClient
{
    NSURLSession* _session;
}

+(KFDClient*)sharedClient
{
    static KFDClient* _client=nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _client=[[KFDClient alloc] init];
    });
    return _client;
}

-(instancetype)init
{
    if (self=[super init]) {
        _session=[NSURLSession sharedSession];
    }
    return self;
}

-(NSURLSessionTask*)registerWithPhoneNubmer:(NSString*)phoneNumber realName:(NSString*)realName checkcode:(NSString*)checkcode successHandler:(KFDRegisterSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSMutableDictionary* parameters=[NSMutableDictionary dictionary];
    [parameters setNotNilObject:phoneNumber forKey:@"mobile"];
    [parameters setNotNilObject:realName forKey:@"realname"];
    [parameters setNotNilObject:checkcode forKey:@"code"];
    NSURLRequest* request=[NSMutableURLRequest postRequestWithURL:[NSString stringWithFormat:@"%@/api-user/register",HOST] bodyParameters:parameters];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if (response.success) {
            if (successHandler) {
                successHandler();
            }
        }else if(failureHandler){
            failureHandler(response);
        }
    }];
#ifdef NETWORKING_ENABLED
    [task resume];
#endif
    return task;
}

-(NSURLSessionTask*)getCheckcodeWithType:(NSString*)type phoneNumber:(NSString *)phoneNumber successHandler:(KFDGetCheckcodeSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSMutableDictionary* parameters=[NSMutableDictionary dictionary];
    [parameters setNotNilObject:phoneNumber forKey:@"mobile"];
    [parameters setObject:type forKey:@"type"];
    NSURLRequest* request=[NSMutableURLRequest getRequestWithURL:[NSString stringWithFormat:@"%@/api-user/code",HOST] parameters:parameters];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if(response.success){
            if(successHandler){
                successHandler();
            }
        }else if(failureHandler){
            failureHandler(response);
        }
    }];
#ifdef NETWORKING_ENABLED
    [task resume];
#endif
    return task;
}

-(NSURLSessionTask*)verifyCheckcode:(NSString*)checkcode withType:(NSString*)type phoneNumber:(NSString *)phoneNumber successHandler:(KFDVerifyCheckcodeSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSMutableDictionary* parameters=[NSMutableDictionary dictionary];
    [parameters setNotNilObject:phoneNumber forKey:@"mobile"];
    [parameters setNotNilObject:type forKey:@"type"];
    [parameters setNotNilObject:checkcode forKey:@"code"];
    NSURLRequest* request=[NSMutableURLRequest getRequestWithURL:[NSString stringWithFormat:@"%@/api-user/checkcode",HOST] parameters:parameters];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if (response.success) {
            if (successHandler) {
                successHandler(response.data[@"token"]);
            }
        }else if (failureHandler){
            failureHandler(response);
        }
    }];
    [task resume];
    return task;
}

-(NSURLSessionTask*)setNickname:(NSString *)nickname password:(NSString *)password successHandler:(KFDSetNicknameAndPasswordSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSString* encryptedPassword=[KFDEncryptor encryptPassword:password];
    NSString* urlEncodedEncryptedPassword=encryptedPassword.URLEncodedString;
    
    NSMutableDictionary* parametersForSigning=[NSMutableDictionary dictionary];
    [parametersForSigning setNotNilObject:nickname forKey:@"nickname"];
    [parametersForSigning setNotNilObject:encryptedPassword forKey:@"password"];
    NSDictionary* fullParametersForSigning=[NSMutableURLRequest fullParametersWithParameters:parametersForSigning];
    NSString* signature=[KFDEncryptor signatureGeneratedFromParameters:fullParametersForSigning];
    
    NSMutableDictionary* parameters=[NSMutableDictionary dictionary];
    [parameters setNotNilObject:nickname forKey:@"nickname"];
    [parameters setNotNilObject:urlEncodedEncryptedPassword forKey:@"password"];
    
    NSString* url=[NSString stringWithFormat:@"%@/api-user-main/set",HOST];
    NSMutableURLRequest* request=[NSMutableURLRequest getRequestWithURL:url parameters:parameters signature:signature];
    NSHTTPCookieStorage* cookieStorage=[NSHTTPCookieStorage sharedHTTPCookieStorage];
    NSArray* cookies=cookieStorage.cookies;
    NSHTTPCookie* token=nil;
    for (NSHTTPCookie* cookie in cookies) {
        if ([cookie.name isEqualToString:@"__TOKEN"]) {
            token=cookie;
        }
    }
    NSArray* cookiesArr=@[token];
    NSDictionary* headerFields=[NSHTTPCookie requestHeaderFieldsWithCookies:cookiesArr];
    [request setValue:headerFields[@"Cookie"] forHTTPHeaderField:@"Cookie"];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if (response.success) {
            if (successHandler) {
                successHandler();
            }
        }else if(failureHandler){
            failureHandler(response);
        }
    }];
#ifdef NETWORKING_ENABLED
    [task resume];
#endif
    return task;
}

-(NSURLSessionTask*)loginWithPhoneNumber:(NSString *)phoneNumber password:(NSString *)password successHandler:(KFDLoginSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSString* encryptedPassword=[KFDEncryptor encryptPassword:password];
    NSString* urlEncodedEncryptedPassword=encryptedPassword.URLEncodedString;
    
    NSMutableDictionary* parametersForSigning=[NSMutableDictionary dictionary];
    [parametersForSigning setNotNilObject:phoneNumber forKey:@"account"];
    [parametersForSigning setNotNilObject:encryptedPassword forKey:@"password"];
    NSDictionary* fullParametersForSigning=[NSMutableURLRequest fullParametersWithParameters:parametersForSigning];
    NSString* signature=[KFDEncryptor signatureGeneratedFromParameters:fullParametersForSigning];
    
    NSMutableDictionary* parameters=[NSMutableDictionary dictionary];
    [parameters setNotNilObject:phoneNumber forKey:@"account"];
    [parameters setNotNilObject:urlEncodedEncryptedPassword forKey:@"password"];
    
    NSURLRequest* request=[NSMutableURLRequest getRequestWithURL:[NSString stringWithFormat:@"%@/api-user/login",HOST] parameters:parameters signature:signature];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if (response.success) {
            if (successHandler) {
                successHandler();
            }
        }else if(failureHandler){
            failureHandler(response);
        }
    }];
#ifdef NETWORKING_ENABLED
    [task resume];
#endif
    return task;
}

-(NSURLSessionTask*)getMarketPriceWithSucessHandler:(KFDGetMarketPriceSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSURLRequest* request=[NSMutableURLRequest getRequestWithURL:[NSString stringWithFormat:@"%@/api-market/price",HOST] parameters:nil];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if (response.success) {
            if (successHandler) {
                NSMutableArray* marketPrices=[NSMutableArray array];
                NSArray* items=((NSDictionary*)response.data)[@"price"];
                for (NSDictionary* item in items) {
                    KFDMarketPrice* marketPrice=[KFDMarketPrice modelObjectFromDictionary:item];
                    [marketPrices addObject:marketPrice];
                }
                successHandler(marketPrices);
            }
        }else if(failureHandler){
            failureHandler(response);
        }
    }];
#ifdef NETWORKING_ENABLED
    [task resume];
#endif
    return task;
}

-(NSURLSessionTask*)getDiagramDataWithType:(NSString *)type lastTime:(NSNumber *)lastTime successHandler:(KFDGetDiagramDataWithTimeSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSMutableDictionary* parameters=[NSMutableDictionary dictionary];
    [parameters setNotNilObject:type forKey:@"typename"];
    [parameters setNotNilObject:lastTime forKey:@"lasttime"];
    NSURLRequest* request=[NSMutableURLRequest getRequestWithURL:[NSString stringWithFormat:@"%@/api-market",HOST] parameters:parameters];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if (response.success) {
            if (successHandler) {
                NSArray* list=response.data[@"list"];
                NSMutableArray* diagramData=[NSMutableArray array];
                for (NSArray* item in list) {
                    KFDDiagramPoint* diagramPoint=[KFDDiagramPoint new];
                    NSString* time=item[0];
                    diagramPoint.date=[NSDate dateWithTimeIntervalSince1970:time.integerValue];
                    NSString* price=item[1];
                    diagramPoint.price=@(price.floatValue);
                    [diagramData addObject:diagramPoint];
                }
                successHandler(diagramData,response.time);
            }
        }else if (failureHandler){
            failureHandler(response);
        }
    }];
#ifdef NETWORKING_ENABLED
    [task resume];
#endif
    return task;
}

-(NSURLSessionTask*)getTradingStrategiesWithMaxCountPerPage:(NSUInteger)count page:(NSUInteger)page successHandler:(KFDGetTradingStrategiesSucessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSMutableDictionary* parameters=[NSMutableDictionary dictionary];
    [parameters setNotNilObject:@(count) forKey:@"ps"];
    [parameters setNotNilObject:@(page) forKey:@"p"];
    NSURLRequest* request=[NSMutableURLRequest getRequestWithURL:[NSString stringWithFormat:@"%@/api-market/strategy",HOST] parameters:parameters];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if (response.success) {
            if (successHandler) {
                NSMutableArray* strategies=[NSMutableArray array];
                NSArray* items=((NSDictionary*)response.data)[@"list"];
                for (NSDictionary* item in items) {
                    KFDTradingStrategy* strategy=[KFDTradingStrategy modelObjectFromDictionary:item];
                    NSInteger time=((NSString*)item[@"dateline"]).integerValue;
                    strategy.date=[NSDate dateWithTimeIntervalSince1970:time];
                    [strategies addObject:strategy];
                }
                successHandler(strategies);
            }
        }else if(failureHandler){
            failureHandler(response);
        }
    }];
#ifdef NETWORKING_ENABLED
    [task resume];
#endif
    return task;
}

-(NSURLSessionTask*)getLiveNewsWithMaxCountPerPage:(NSUInteger)count page:(NSUInteger)page successHandler:(KFDGetAliveNewsSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSMutableDictionary* parameters=[NSMutableDictionary dictionary];
    [parameters setNotNilObject:@(count) forKey:@"ps"];
    [parameters setNotNilObject:@(page) forKey:@"p"];
    NSURLRequest* request=[NSMutableURLRequest getRequestWithURL:[NSString stringWithFormat:@"%@/api-market/info",HOST] parameters:parameters];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if (response.success) {
            if (successHandler) {
                NSMutableArray* news=[NSMutableArray array];
                NSArray* items=((NSDictionary*)response.data)[@"list"];
                for (NSDictionary*item in items) {
                    KFDLiveNewsPiece* piece=[KFDLiveNewsPiece modelObjectFromDictionary:item];
                    [news addObject:piece];
                }
                successHandler(news);
            }
        }else if (failureHandler){
            
        }
    }];
#ifdef NETWORKING_ENABLED
    [task resume];
#endif
    return task;
}

-(NSURLSessionTask*)getFinancialInfoWithDate:(NSDate *)date successHandler:(KFDGetFinancialInfoSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSMutableDictionary* parameters=[NSMutableDictionary dictionary];
    [parameters setNotNilObject:date.yearMonthDay forKey:@"date"];
    NSURLRequest* request=[NSMutableURLRequest getRequestWithURL:[NSString stringWithFormat:@"%@/api-market/finance",HOST] parameters:parameters];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if (response.success) {
            if (successHandler) {
                NSMutableArray* financialData=[NSMutableArray array];
                NSMutableArray* holidayForecasts=[NSMutableArray array];
                NSMutableArray* financialEvents=[NSMutableArray array];
                NSDictionary* info=response.data;
                NSArray* financialDataRaw=info[@"finance"];
                NSArray* holidayForecastsRaw=info[@"holiday"];
                NSArray* financialEventsRaw=info[@"event"];
                for (NSDictionary* financialDatumRaw in financialDataRaw) {
                    KFDFinancialDatum* financialDatum=[KFDFinancialDatum modelObjectFromDictionary:financialDatumRaw];
                    [financialData addObject:financialDatum];
                }
                for (NSDictionary* holidayForecastRaw in holidayForecastsRaw) {
                    KFDHolidayForecast* holidayForecast=[KFDHolidayForecast modelObjectFromDictionary:holidayForecastRaw];
                    NSInteger time=((NSString*)holidayForecastRaw[@"time"]).integerValue;
                    if (time>0) {
                        holidayForecast.date=[NSDate dateWithTimeIntervalSince1970:time];
                    }
                    [holidayForecasts addObject:holidayForecast];
                }
                for (NSDictionary* financialEventRaw in financialEventsRaw) {
                    KFDFinancialEvent* financialEvent=[KFDFinancialEvent modelObjectFromDictionary:financialEventRaw];
                    [financialEvents addObject:financialEvent];
                }
                successHandler(financialData,holidayForecasts,financialEvents);
            }
        }else if(failureHandler){
            failureHandler(response);
        }
    }];
#ifdef NETWORKING_ENABLED
    [task resume];
#endif
    return task;
}

-(NSURLSessionTask*)getDiagramDataWithType:(NSString *)type period:(KFDDiagramDataPeriod)period beforeTime:(NSInteger)time successHandler:(KFDGetDiagramDataSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSMutableDictionary* parameters=[NSMutableDictionary dictionary];
    [parameters setNotNilObject:type forKey:@"typename"];
    [parameters setNotNilObject:[NSString stringWithFormat:@"%ld",(long)period] forKey:@"timetype"];
    [parameters setNotNilObject:@(time) forKey:@"beforetime"];
    NSURLRequest* request=[NSMutableURLRequest getRequestWithURL:[NSString stringWithFormat:@"%@/api-market/kchart",HOST] parameters:parameters];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if(response.success){
            if(successHandler){
                NSMutableArray* diagramPoints=[NSMutableArray array];
                NSArray* list=response.data[@"list"];
                for (NSDictionary* item in list) {
                    KFDDiagramPoint* diagramPoint=[KFDDiagramPoint modelObjectFromDictionary:item];
                    [diagramPoints addObject:diagramPoint];
                }
                successHandler(diagramPoints);
            }
        }else if(failureHandler){
            failureHandler(response);
        }
    }];
#ifdef NETWORKING_ENABLED
    [task resume];
#endif
    return task;
}

-(NSURLSessionTask*)getLiveUrlWithSuccessHandler:(KFDGetLiveUrlSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSURLRequest* request=[NSMutableURLRequest getRequestWithURL:[NSString stringWithFormat:@"%@/api-main/chat",HOST] parameters:nil];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if (response.success) {
            if (successHandler) {
                NSString* url=response.data[@"url"];
                successHandler(url);
            }
        }else if(failureHandler){
            failureHandler(response);
        }
    }];
#ifdef NETWORKING_ENABLED
    [task resume];
#endif
    return task;
}

-(NSURLSessionTask*)getAnnouncementListWithMaxCount:(NSUInteger)maxCount page:(NSUInteger)page successHandler:(KFDGetAnnouncementListSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSMutableDictionary* parameters=[NSMutableDictionary dictionary];
    [parameters setNotNilObject:@(maxCount) forKey:@"ps"];
    [parameters setNotNilObject:@(page) forKey:@"p"];
    NSURLRequest* request=[NSMutableURLRequest getRequestWithURL:[NSString stringWithFormat:@"%@/api-market/notice",HOST] parameters:parameters];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if (response.success) {
            if (successHandler) {
                NSMutableArray* announcementList=[NSMutableArray array];
                NSArray* list=response.data[@"list"];
                for (NSDictionary* item in list) {
                    KFDAnnouncementBrief* announcementBrief=[KFDAnnouncementBrief modelObjectFromDictionary:item];
                    NSString* time=item[@"dateline"];
                    announcementBrief.date=[NSDate dateWithTimeIntervalSince1970:time.integerValue];
                    [announcementList addObject:announcementBrief];
                }
                successHandler(announcementList);
            }
        }else if(failureHandler){
            failureHandler(response);
        }
    }];
#ifdef NETWORKING_ENABLED
    [task resume];
#endif
    return  task;
}

-(NSURLSessionTask*)getAnnouncementWithId:(NSString *)id successHandler:(KFDGetAnnouncementSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSMutableDictionary* parameteres=[NSMutableDictionary dictionary];
    [parameteres setNotNilObject:id forKey:@"id"];
    NSURLRequest* request=[NSMutableURLRequest getRequestWithURL:[NSString stringWithFormat:@"%@/api-market/noticeView",HOST] parameters:parameteres];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if(response.success){
            if(successHandler){
                NSDictionary* notice=response.data[@"notice"];
                KFDAnnouncement* announcement=[KFDAnnouncement modelObjectFromDictionary:notice];
                NSString* time=notice[@"dateline"];
                announcement.date=[NSDate dateWithTimeIntervalSince1970:time.integerValue];
                successHandler(announcement);
            }
        }else if(failureHandler){
            failureHandler(response);
        }
    }];
#ifdef NETWORKING_ENABLED
    [task resume];
#endif
    return task;
}

-(NSURLSessionTask*)getETFHoldingsWithTypeId:(NSString *)typeId maxCount:(NSUInteger)maxCount page:(NSUInteger)page successHandler:(KFDGetETFHoldingsSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSMutableDictionary* parameters=[NSMutableDictionary dictionary];
    [parameters setNotNilObject:typeId forKey:@"typeid"];
    [parameters setNotNilObject:@(maxCount) forKey:@"ps"];
    [parameters setNotNilObject:@(page) forKey:@"p"];
    NSURLRequest* request=[NSMutableURLRequest getRequestWithURL:[NSString stringWithFormat:@"%@/api-find-main/eft",HOST] parameters:parameters];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if (response.success) {
            if (successHandler) {
                NSMutableArray* holdings=[NSMutableArray array];
                NSArray* list=response.data[@"list"];
                for (NSDictionary* item in list) {
                    KFDETFHolding* holding=[KFDETFHolding modelObjectFromDictionary:item];
                    NSString* time=item[@"dateline"];
                    holding.date=[NSDate dateWithTimeIntervalSince1970:time.integerValue];
                    [holdings addObject:holding];
                }
                successHandler(holdings);
            }
        }else if(failureHandler){
            failureHandler(response);
        }
    }];
#ifdef NETWORKING_ENABLED
    [task resume];
#endif
    return task;
}

-(NSURLSessionTask*)updateAccountInfoWithNickname:(NSString *)nickname province:(NSString *)province city:(NSString *)city avatar:(NSString *)avatar gender:(NSNumber*)gender clientId:(NSString*)clientId pushToken:(NSString*)pushToken successHandler:(KFDUpdateAccountInfoSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSMutableDictionary* parameters=[NSMutableDictionary dictionary];
    [parameters setNotNilObject:nickname forKey:@"nickname"];
    [parameters setNotNilObject:province forKey:@"province"];
    [parameters setNotNilObject:city forKey:@"city"];
    [parameters setNotNilObject:avatar forKey:@"face"];
    [parameters setNotNilObject:gender forKey:@"sex"];
    [parameters setNotNilObject:clientId forKey:@"clientid"];
    [parameters setNotNilObject:pushToken forKey:@"pushtoken"];
    NSURLRequest* request=[NSMutableURLRequest postRequestWithURL:[NSString stringWithFormat:@"%@/api-user-main/update",HOST] bodyParameters:parameters];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if (response.success) {
            if (successHandler) {
                successHandler();
            }
        }else if(failureHandler){
            failureHandler(response);
        }
    }];
#ifdef NETWORKING_ENABLED
    [task resume];
#endif
    return task;
}

-(NSURLSessionTask*)getInvestmentCommunityPostsWithMaxCount:(NSUInteger)maxCount page:(NSUInteger)page successHandler:(KFDGetInvestmentCommunityPostsSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSMutableDictionary* parameters=[NSMutableDictionary dictionary];
    [parameters setNotNilObject:@(maxCount) forKey:@"ps"];
    [parameters setNotNilObject:@(page) forKey:@"p"];
    NSURLRequest* request=[NSMutableURLRequest getRequestWithURL:[NSString stringWithFormat:@"%@/api-quan-topic",HOST] parameters:parameters];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if (response.success) {
            if (successHandler) {
                NSArray* list=response.data[@"list"];
                NSMutableArray* posts=[NSMutableArray array];
                for (NSDictionary* item in list) {
                    KFDInvestmentCommunityPost* post=[KFDInvestmentCommunityPost modelObjectFromDictionary:item];
                    post.likes=((NSString*)item[@"likes"]).integerValue;
                    post.comments=((NSString*)item[@"comments"]).integerValue;
                    post.date=[NSDate dateWithTimeIntervalSince1970:((NSString*)item[@"dateline"]).integerValue];
                    NSMutableArray* comments=[NSMutableArray array];
                    NSArray* rawComments=item[@"newcomments"];
                    if (rawComments&&![rawComments isKindOfClass:[NSNull class]]) {
                        for (NSDictionary* commentRaw in rawComments) {
                            KFDICPostComment* comment=[KFDICPostComment modelObjectFromDictionary:commentRaw];
                            [comments addObject:comment];
                        }
                        post.newcomments=comments;
                    }
                    [posts addObject:post];
                }
                successHandler(posts);
            }
        }else if(failureHandler){
            failureHandler(response);
        }
    }];
#ifdef NETWORKING_ENABLED
    [task resume];
#endif
    return task;
}

-(NSURLSessionTask*)publishInvestmentCommunityPostWithContent:(NSString *)content pictures:(NSArray *)pictures successHandler:(KFDPublishPostSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSMutableDictionary* parameters=[NSMutableDictionary dictionary];
    [parameters setNotNilObject:content forKey:@"content"];
    KFDStringConcatenator* concatenator=[KFDStringConcatenator concatenatorWithSeparator:@","];
    [parameters setNotNilObject:[concatenator concatenateStringsInArray:pictures] forKey:@"picid"];
    NSURLRequest* request=[NSMutableURLRequest postRequestWithURL:[NSString stringWithFormat:@"%@/api-quan-topic/add",HOST] bodyParameters:parameters];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if (response.success) {
            if (successHandler) {
                NSString* postId=response.data[@"tid"];
                successHandler(postId);
            }
        }else if(failureHandler){
            failureHandler(response);
        }
    }];
#ifdef NETWORKING_ENABLED
    [task resume];
#endif
    return task;
}

-(NSURLSessionTask*)uploadInvestmentCommunityPostPicture:(UIImage *)picture successHandler:(KFDUploadInvestmentCommunityPostPictureSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSData* imageData=UIImageJPEGRepresentation(picture, 90);
    int i=1;
    while (imageData.length>200000) {
        imageData=UIImageJPEGRepresentation(picture, pow(0.5, i));
        i++;
        if (i>10) {
            [[NSNotificationCenter defaultCenter] postNotificationName:KFDImageSizeExceedLimitNotification object:nil];
            break;
        }
    }
    if (i<=10) {
        NSMutableURLRequest* request=[NSMutableURLRequest postRequestWithURL:[NSString stringWithFormat:@"%@/api-quan-topic/upload",HOST] urlParameters:nil];
        
        NSString* BoundaryConstant=@"----------";
        // set Content-Type in HTTP header
        NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", BoundaryConstant];
        [request setValue:contentType forHTTPHeaderField: @"Content-Type"];
        
        // post body
        NSMutableData *body = [NSMutableData data];
        // add image data
        if (imageData) {
            [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"avatar.jpg\"\r\n", @"picture"] dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:imageData];
            [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
        }
        
        [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
        
        // setting the body of the post to the reqeust
        [request setHTTPBody:body];
        
        // set the content-length
        NSString *postLength = [NSString stringWithFormat:@"%ld", (unsigned long)[body length]];
        [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
        
        NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
            if (response.success) {
                if (successHandler) {
                    NSString* pictureId=response.data[@"id"];
                    successHandler(pictureId);
                }
            }else if(failureHandler){
                failureHandler(response);
            }
        }];
#ifdef NETWORKING_ENABLED
        [task resume];
#endif
        return task;
    }
    return nil;
}

-(NSURLSessionTask*)praiseInvestmentCommunityPost:(NSString *)postId successHandler:(KFDPraiseInvestmentCommunityPostSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSMutableDictionary* parameters=[NSMutableDictionary dictionary];
    [parameters setNotNilObject:postId forKey:@"tid"];
    NSURLRequest* request=[NSMutableURLRequest getRequestWithURL:[NSString stringWithFormat:@"%@/api-quan-topic/like",HOST] parameters:parameters];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if (response.success) {
            if (successHandler) {
                NSString* likes=response.data[@"likes"];
                successHandler(likes.integerValue);
            }
        }else if(failureHandler){
            failureHandler(response);
        }
    }];
#ifdef NETWORKING_ENABLED
    [task resume];
#endif
    return task;
}

-(NSURLSessionTask*)cancelPraiseInvestmentCommunityPost:(NSString *)postId successHandler:(KFDCancelPraiseInvestmentCommunityPostSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSMutableDictionary* parameters=[NSMutableDictionary dictionary];
    [parameters setNotNilObject:postId forKey:@"tid"];
    NSURLRequest* request=[NSMutableURLRequest getRequestWithURL:[NSString stringWithFormat:@"%@/api-quan-topic/unlike",HOST] parameters:parameters];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if (response.success) {
            if (successHandler) {
                NSString* likes=response.data[@"likes"];
                successHandler(likes.integerValue);
            }
        }else if (failureHandler){
            failureHandler(response);
        }
    }];
#ifdef NETWORKING_ENABLED
    [task resume];
#endif
    return task;
}

-(NSURLSessionTask*)getPreferentialActivitiesWithType:(NSString *)type maxCount:(NSUInteger)maxCount page:(NSUInteger)page successHandler:(KFDGetPreferentialActivitiesSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSMutableDictionary* parameters=[NSMutableDictionary dictionary];
    [parameters setNotNilObject:type forKey:@"typeid"];
    NSURLRequest* request=[NSMutableURLRequest getRequestWithURL:[NSString stringWithFormat:@"%@/api-find-active/list",HOST] parameters:parameters];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if (response.success) {
            if (successHandler) {
                NSMutableArray* activities=[NSMutableArray array];
                NSArray* list=response.data[@"list"];
                for (NSDictionary* item in list) {
                    KFDPreferentialActivity* activity=[KFDPreferentialActivity modelObjectFromDictionary:item];
                    [activities addObject:activity];
                }
                successHandler(activities);
            }
        }else if (failureHandler){
            failureHandler(response);
        }
    }];
#ifdef NETWORKING_ENABLED
    [task resume];
#endif
    return task;
}

-(NSURLSessionTask*)getAccountInfoWithSuccessHandler:(KFDGetAccountInfoSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSURLRequest* request=[NSMutableURLRequest getRequestWithURL:[NSString stringWithFormat:@"%@/api-user-main/my",HOST] parameters:nil];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if (response.success) {
            if (successHandler) {
                NSDictionary* accountInfoRaw=response.data[@"user"];
                KFDAccountInfo* accountInfo=[KFDAccountInfo modelObjectFromDictionary:accountInfoRaw];
//                NSString* isemailRaw=accountInfoRaw[@"isemail"];
//                accountInfo.isemail=[isemailRaw isEqualToString:@"1"]?YES:NO;
                successHandler(accountInfo);
            }
        }else if (failureHandler){
            failureHandler(response);
        }
    }];
#ifdef NETWORKING_ENABLED
    [task resume];
#endif
    return task;
}

-(NSURLSessionTask*)setPassword:(NSString *)password token:(NSString*)token successHandler:(KFDSetPasswordSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSString* encryptedPassword=[KFDEncryptor encryptPassword:password];
    NSMutableDictionary* parametersForSigning=[NSMutableDictionary dictionary];
    [parametersForSigning setNotNilObject:encryptedPassword forKey:@"password"];
    [parametersForSigning setNotNilObject:token forKey:@"token"];
    NSDictionary* fullParametersForSigning=[NSMutableURLRequest fullParametersWithParameters:parametersForSigning];
    NSString* signature=[KFDEncryptor signatureGeneratedFromParameters:fullParametersForSigning];
    NSMutableDictionary* parameters=[NSMutableDictionary dictionary];
    [parameters setNotNilObject:encryptedPassword.URLEncodedString forKey:@"password"];
    [parameters setNotNilObject:token forKey:@"token"];
    NSURLRequest* request=[NSMutableURLRequest postRequestWithURL:[NSString stringWithFormat:@"%@/api-user/setpassword",HOST] bodyParameters:parameters signature:signature];
//    NSURLRequest* request=[NSMutableURLRequest getRequestWithURL:[NSString stringWithFormat:@"%@/api-user/setpassword",HOST] parameters:parameters signature:signature];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if (response.success) {
            if (successHandler) {
                successHandler();
            }
        }else if (failureHandler){
            failureHandler(response);
        }
    }];
#ifdef NETWORKING_ENABLED
    [task resume];
#endif
    return task;
}

-(NSURLSessionTask*)getFinancialServiceInterfaceWithSuccessHandler:(KFDGetFinancialServiceInterfaceSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSURLRequest* request=[NSMutableURLRequest getRequestWithURL:[NSString stringWithFormat:@"%@/api-user-main/get",HOST] parameters:nil];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if (response.success) {
            if (successHandler) {
                successHandler(response.data[@"withdraw"],response.data[@"injection"]);
            }
        }else if (failureHandler){
            failureHandler(response);
        }
    }];
#ifdef NETWORKING_ENABLED
    [task resume];
#endif
    return task;
}

-(NSURLSessionTask*)bindEmail:(NSString *)email successHandler:(KFDBindEmailSuccessHandler)successHandler failulreHandler:(KFDRequestFailureHandler)failureHandler
{
    NSMutableDictionary* parameters=[NSMutableDictionary dictionary];
    [parameters setNotNilObject:email forKey:@"email"];
    NSURLRequest* request=[NSMutableURLRequest getRequestWithURL:[NSString stringWithFormat:@"%@/api-user-main/email",HOST] parameters:parameters];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if (response.success) {
            if (successHandler) {
                successHandler();
            }
        }else if (failureHandler){
            failureHandler(response);
        }
    }];
#ifdef NETWORKING_ENABLED
    [task resume];
#endif
    return task;
}

-(NSURLSessionTask*)getLiveRoomsWithSuccessHandler:(KFDGetLivesSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSURLRequest* request=[NSMutableURLRequest getRequestWithURL:[NSString stringWithFormat:@"%@/api-main/room",HOST] parameters:nil];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if (response.success) {
            if (successHandler) {
                NSMutableArray* rooms=[NSMutableArray array];
                NSArray* list=response.data[@"list"];
                for (NSDictionary* item in list) {
                    KFDLiveRoom* room=[KFDLiveRoom modelObjectFromDictionary:item];
                    room.isDefault=[item[@"isauto"] isEqualToString:@"1"]?YES:NO;
                    [rooms addObject:room];
                }
                successHandler(rooms);
            }
        }else if (failureHandler){
            failureHandler(response);
        }
    }];
#ifdef NETWORKING_ENABLED
    [task resume];
#endif
    return task;
}

-(NSURLSessionTask*)getFAQsWithSuccessHandler:(KFDGetFAQsSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSURLRequest* request=[NSMutableURLRequest getRequestWithURL:[NSString stringWithFormat:@"%@/api-main/help",HOST] parameters:nil];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if (response.success) {
            if (successHandler) {
                NSMutableArray* faqs=[NSMutableArray array];
                NSArray* list=response.data[@"help"];
                for (NSDictionary* item in list) {
                    KFDFaq* faq=[KFDFaq modelObjectFromDictionary:item];
                    [faqs addObject:faq];
                }
                successHandler(faqs);
            }
        }else if (failureHandler){
            failureHandler(response);
        }
    }];
#ifdef NETWORKING_ENABLED
    [task resume];
#endif
    return task;
}

-(NSURLSessionTask*)getAboutUsWithSuccessHandler:(KFDGetAboutUseSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSURLRequest* request=[NSMutableURLRequest getRequestWithURL:[NSString stringWithFormat:@"%@/api-main/about",HOST] parameters:nil];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if (response.success) {
            if (successHandler) {
                KFDAboutUs* aboutUs=[KFDAboutUs modelObjectFromDictionary:response.data];
                successHandler(aboutUs);
            }
        }else if (failureHandler){
            failureHandler(response);
        }
    }];
#ifdef NETWORKING_ENABLED
    [task resume];
#endif
    return task;
}

-(NSURLSessionTask*)joinPreferentialActivity:(NSString *)activityId successHandler:(KFDJoinPreferentialActivitySuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSMutableDictionary* parameters=[NSMutableDictionary dictionary];
    [parameters setNotNilObject:activityId forKey:@"id"];
    NSURLRequest* request=[NSMutableURLRequest getRequestWithURL:[NSString stringWithFormat:@"%@/api-find-active/join",HOST] parameters:parameters];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if (response.success) {
            if (successHandler) {
                successHandler();
            }
        }else if (failureHandler){
            failureHandler(response);
        }
    }];
#ifdef NETWORKING_ENABLED
    [task resume];
#endif
    return task;
}

-(NSURLSessionTask*)getMyPreferentialActivitiesWithMaxCount:(NSUInteger)maxCount page:(NSUInteger)page successHandler:(KFDGetMyPreferentialActivitiesSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSMutableDictionary* parameters=[NSMutableDictionary dictionary];
    [parameters setNotNilObject:@(maxCount) forKey:@"ps"];
    [parameters setNotNilObject:@(page) forKey:@"p"];
    NSURLRequest* request=[NSMutableURLRequest getRequestWithURL:[NSString stringWithFormat:@"%@/api-find-active/my",HOST] parameters:parameters];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if (response.success) {
            if (successHandler) {
                NSMutableArray* activities=[NSMutableArray array];
                NSArray* list=response.data[@"list"];
                for (NSDictionary* item in list) {
                    KFDPreferentialActivity* activity=[KFDPreferentialActivity modelObjectFromDictionary:item];
                    [activities addObject:activity];
                }
                successHandler(activities);
            }
        }else if (failureHandler){
            failureHandler(response);
        }
    }];
#ifdef NETWORKING_ENABLED
    [task resume];
#endif
    return task;
}

-(NSURLSessionTask*)commentICPost:(NSString *)postId userId:(NSString *)userId content:(NSString *)content successHandler:(KFDCommentICPostSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSMutableDictionary* parameters=[NSMutableDictionary dictionary];
    [parameters setNotNilObject:postId forKey:@"tid"];
    [parameters setNotNilObject:userId forKey:@"cuid"];
    [parameters setNotNilObject:content forKey:@"content"];
    NSURLRequest* request=[NSMutableURLRequest postRequestWithURL:[NSString stringWithFormat:@"%@/api-quan-comment/add",HOST] bodyParameters:parameters];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if (response.success) {
            if (successHandler) {
                successHandler();
            }
        }else if (failureHandler){
            failureHandler(response);
        }
    }];
#ifdef NETWORKING_ENABLED
    [task resume];
#endif
    return task;
}

-(NSURLSessionTask*)feedbackWithType:(KFDFeedbackType)type content:(NSString *)content successHandler:(KFDFeedbackSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSMutableDictionary* parameters=[NSMutableDictionary dictionary];
    [parameters setNotNilObject:@(type) forKey:@"typeid"];
    [parameters setNotNilObject:content forKey:@"content"];
    NSURLRequest* request=[NSMutableURLRequest postRequestWithURL:[NSString stringWithFormat:@"%@/api-user/feedback",HOST] bodyParameters:parameters];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if (response.success) {
            if (successHandler) {
                successHandler();
            }
        }else if (failureHandler){
            failureHandler(response);
        }
    }];
#ifdef NETWORKING_ENABLED
    [task resume];
#endif
    return task;
}

-(NSURLSessionTask*)getVIPInfoWithSuccessHandler:(KFDGetVIPInfoSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSURLRequest* request=[NSMutableURLRequest getRequestWithURL:[NSString stringWithFormat:@"%@/api-find-vip/get",HOST] parameters:nil];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if (response.success) {
            if (successHandler) {
                NSString* isVIP=response.data[@"isvip"];
                NSString* isQualified=response.data[@"isto"];
                successHandler(isVIP.boolValue,isQualified.boolValue);
            }
        }else if (failureHandler){
            failureHandler(response);
        }
    }];
#ifdef NETWORKING_ENABLED
    [task resume];
#endif
    return task;
}

-(NSURLSessionTask*)applyForVIPWithSuccessHandler:(KFDApplyForVIPSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSURLRequest* request=[NSMutableURLRequest getRequestWithURL:[NSString stringWithFormat:@"%@/api-find-vip/apply",HOST] parameters:nil];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if (response.success) {
            if (successHandler) {
                successHandler();
            }
        }else if (failureHandler){
            failureHandler(response);
        }
    }];
#ifdef NETWORKING_ENABLED
    [task resume];
#endif
    return task;
}

-(NSURLSessionTask*)getAddressWithSuccessHandler:(KFDGetAddressSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSURLRequest* request=[NSMutableURLRequest getRequestWithURL:[NSString stringWithFormat:@"%@/api-user/address",HOST] parameters:nil];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if (response.success) {
            if (successHandler) {
                successHandler(response.data);
            }
        }else if (failureHandler){
            failureHandler(response);
        }
    }];
#ifdef NETWORKING_ENABLED
    [task resume];
#endif
    return task;
}

-(NSURLSessionTask*)getTeachersWithMaxCount:(NSUInteger)maxCount page:(NSUInteger)page successHandler:(KFDGetTeachersSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSMutableDictionary* parameters=[NSMutableDictionary dictionary];
    [parameters setNotNilObject:@(maxCount) forKey:@"ps"];
    [parameters setNotNilObject:@(page) forKey:@"p"];
    NSURLRequest* request=[NSMutableURLRequest getRequestWithURL:[NSString stringWithFormat:@"%@/api-find-vip/teacher",HOST] parameters:parameters];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if (response.success) {
            if (successHandler) {
                NSMutableArray* teachers=[NSMutableArray array];
                NSArray* list=response.data[@"list"];
                for (NSDictionary* item in list) {
                    KFDTeacher* teacher=[KFDTeacher modelObjectFromDictionary:item];
                    [teachers addObject:teacher];
                }
                successHandler(teachers);
            }
        }else if (failureHandler){
            failureHandler(response);
        }
    }];
#ifdef NETWORKING_ENABLED
    [task resume];
#endif
    return task;
}

-(NSURLSessionTask*)chooseTeacher:(NSString *)teacherId successHandler:(KFDChooseTeacherSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSMutableDictionary* parameters=[NSMutableDictionary dictionary];
    [parameters setNotNilObject:teacherId forKey:@"id"];
    NSURLRequest* request=[NSMutableURLRequest getRequestWithURL:[NSString stringWithFormat:@"%@/api-find-vip/choose",HOST] parameters:parameters];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if(response.success){
            if (successHandler) {
                successHandler();
            }
        }else if (failureHandler){
            failureHandler(response);
        }
    }];
#ifdef NETWORKING_ENABLED
    [task resume];
#endif
    return task;
}

-(NSURLSessionTask*)clearChatLogWithSuccessHandler:(KFDClearChatLogSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSURLRequest* request=[NSMutableURLRequest getRequestWithURL:[NSString stringWithFormat:@"%@/api-user-main/clearChat",HOST] parameters:nil];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if (response.success) {
            if (successHandler) {
                successHandler();
            }
        }else if (failureHandler){
            failureHandler(response);
        }
    }];
#ifdef NETWORKING_ENABLED
    [task resume];
#endif
    return task;
}

-(NSURLSessionTask*)getDetailedMarketPriceOfType:(NSString *)type successHandler:(KFDGetDetailedMarketPriceSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSMutableDictionary* parameters=[NSMutableDictionary dictionary];
    [parameters setNotNilObject:type forKey:@"typename"];
    NSURLRequest* request=[NSMutableURLRequest getRequestWithURL:[NSString stringWithFormat:@"%@/api-market/getprice",HOST] parameters:parameters];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if (response.success) {
            if (successHandler) {
                KFDDetailedMarketPrice* price=[KFDDetailedMarketPrice modelObjectFromDictionary:response.data[@"price"]];
                successHandler(price);
            }
        }else if (failureHandler){
            failureHandler(response);
        }
    }];
#ifdef NETWORKING_ENABLED
    [task resume];
#endif
    return task;
}

-(NSURLSessionTask*)getBanksWithSuccessHandler:(KFDGetBanksSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSURLRequest* request=[NSMutableURLRequest getRequestWithURL:[NSString stringWithFormat:@"%@/api-user-main/getbank",HOST] parameters:nil];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if (response.success) {
            if (successHandler) {
                successHandler(response.data[@"bank"]);
            }
        }else if (failureHandler){
            failureHandler(response);
        }
    }];
#ifdef NETWORKING_ENABLED
    [task resume];
#endif
    return task;
}

-(NSURLSessionTask*)getFinancialCalendarDatesWithSuccessHandler:(KFDGetFinancialCalendarDatesSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSURLRequest* request=[NSMutableURLRequest getRequestWithURL:[NSString stringWithFormat:@"%@/api-market/financeDate",HOST] parameters:nil];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if (response.success) {
            if (successHandler) {
//                successHandler(response.data[@"list"]);
                NSMutableArray* dates=[NSMutableArray array];
                NSArray* list=response.data[@"list"];
                for (NSDictionary* item in list) {
                    NSString* time=item[@"time"];
                    NSDate* date=[NSDate dateWithTimeIntervalSince1970:time.integerValue];
                    [dates addObject:date];
                }
                successHandler(dates);
            }
        }else if (failureHandler){
            failureHandler(response);
        }
    }];
#ifdef NETWORKING_ENABLED
    [task resume];
#endif
    return task;
}

-(NSURLSessionTask*)uploadAvatar:(UIImage*)avatar successHandler:(KFDUploadAvatarSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSData* imageData=UIImageJPEGRepresentation(avatar, 90);
    int i=1;
    while (imageData.length>200000) {
        imageData=UIImageJPEGRepresentation(avatar, pow(0.5, i));
        i++;
        if (i>10) {
            [[NSNotificationCenter defaultCenter] postNotificationName:KFDImageSizeExceedLimitNotification object:nil];
            break;
        }
    }
    if (i<=10) {
        NSMutableURLRequest* request=[NSMutableURLRequest postRequestWithURL:[NSString stringWithFormat:@"%@/api-user-main/face",HOST] urlParameters:nil];
        
        NSString* BoundaryConstant=@"----------";
        // set Content-Type in HTTP header
        NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", BoundaryConstant];
        [request setValue:contentType forHTTPHeaderField: @"Content-Type"];
        
        // post body
        NSMutableData *body = [NSMutableData data];
        // add image data
        if (imageData) {
            [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"avatar.jpg\"\r\n", @"picture"] dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:imageData];
            [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
        }
        
        [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
        
        // setting the body of the post to the reqeust
        [request setHTTPBody:body];
        
        // set the content-length
        NSString *postLength = [NSString stringWithFormat:@"%ld", (unsigned long)[body length]];
        [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
        
        NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
            if (response.success) {
                if (successHandler) {
                    NSString* pictureId=response.data[@"face"];
                    successHandler(pictureId);
                }
            }else if(failureHandler){
                failureHandler(response);
            }
        }];
#ifdef NETWORKING_ENABLED
        [task resume];
#endif
        return task;
    }
    return nil;
}

-(NSURLSessionTask*)uploadImage:(UIImage *)image type:(NSString*)type successHandler:(KFDUploadImageSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSData* imageData=UIImageJPEGRepresentation(image, 0.5);
    int i=1;
    while (imageData.length>200000) {
        imageData=UIImageJPEGRepresentation(image, pow(0.5, i));
        i++;
        if (i>10) {
            [[NSNotificationCenter defaultCenter] postNotificationName:KFDImageSizeExceedLimitNotification object:nil];
            break;
        }
    }
    if (i<=10) {
        NSMutableDictionary* parameters=[NSMutableDictionary dictionary];
        [parameters setNotNilObject:type forKey:@"type"];
        NSMutableURLRequest* request=[NSMutableURLRequest postRequestWithURL:[NSString stringWithFormat:@"%@/api-upload/image",HOST] urlParameters:parameters];
        
        NSString* BoundaryConstant=@"----------";
        // set Content-Type in HTTP header
        NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", BoundaryConstant];
        [request setValue:contentType forHTTPHeaderField: @"Content-Type"];
        
        // post body
        NSMutableData *body = [NSMutableData data];
        // add image data
        if (imageData) {
            [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"avatar.jpg\"\r\n", @"picture"] dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:imageData];
            [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
        }
        
        [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
        
        // setting the body of the post to the reqeust
        [request setHTTPBody:body];
        
        // set the content-length
        NSString *postLength = [NSString stringWithFormat:@"%ld", (unsigned long)[body length]];
        [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
        
        NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
            if (response.success) {
                if (successHandler) {
                    NSString* url=response.data[@"picture"];
                    successHandler(url);
                }
            }else if(failureHandler){
                failureHandler(response);
            }
        }];
#ifdef NETWORKING_ENABLED
        [task resume];
#endif
        return task;
    }
    return nil;
}

-(NSURLSessionTask*)setBankAccountInfo:(KFDBankAccountInfo *)bankInfo successHandler:(KFDSetBankSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSMutableDictionary* parameters=[NSMutableDictionary dictionary];
    [parameters setNotNilObject:bankInfo.bank_name forKey:@"bank_name"];
    [parameters setNotNilObject:bankInfo.account forKey:@"account"];
    [parameters setNotNilObject:bankInfo.branch forKey:@"branch"];
    [parameters setNotNilObject:bankInfo.idcard_main forKey:@"idcard_main"];
    [parameters setNotNilObject:bankInfo.idcard_side forKey:@"idcard_side"];
    [parameters setNotNilObject:bankInfo.province forKey:@"province"];
    [parameters setNotNilObject:bankInfo.city forKey:@"city"];
    [parameters setNotNilObject:bankInfo.district forKey:@"district"];
    NSURLRequest* request=[NSMutableURLRequest postRequestWithURL:[NSString stringWithFormat:@"%@/api-user-main/dobank",HOST] bodyParameters:parameters];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if (response.success) {
            if (successHandler) {
                successHandler();
            }
        }else if (failureHandler){
            failureHandler(response);
        }
    }];
#ifdef NETWORKING_ENABLED
    [task resume];
#endif
    return task;
}

-(NSURLSessionTask*)getFinancialServiceCookieWithSuccessHandler:(KFDGetFinancialServiceCookieSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSURLRequest* request=[NSMutableURLRequest getRequestWithURL:[NSString stringWithFormat:@"%@/api-user-main/tologin",HOST] parameters:nil];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if (response.success) {
            if (successHandler) {
                successHandler(response.data[@"name"],response.data[@"value"]);
            }
        }else if (failureHandler){
            failureHandler(response);
        }
    }];
#ifdef NETWORKING_ENABLED
    [task resume];
#endif
    return task;
}

-(NSURLSessionTask*)getAuxiliaryFunctionSettingsWithSuccessHandler:(KFDGetAuxiliaryFunctionSettingsSuccessHanler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSURLRequest* request=[NSMutableURLRequest getRequestWithURL:[NSString stringWithFormat:@"%@/api-user-main/getconfig",HOST] parameters:nil];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if (response.success) {
            if (successHandler) {
                KFDAuxiliaryFunctionSettings* settings=[KFDAuxiliaryFunctionSettings modelObjectFromDictionary:response.data[@"config"]];
                successHandler(settings);
            }
        }else if (failureHandler){
            failureHandler(response);
        }
    }];
#ifdef NETWORKING_ENABLED
    [task resume];
#endif
    return task;
}

-(NSURLSessionTask*)updateAuxiliaryFunctionSettings:(KFDAuxiliaryFunctionSettings *)settings successHandler:(KFDUpdateAuxiliaryFunctionSettingsSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHander
{
    NSMutableDictionary* parameters=[NSMutableDictionary dictionary];
    [parameters setNotNilObject:@(settings.isphoto) forKey:@"isphoto"];
    [parameters setNotNilObject:@(settings.iswifi) forKey:@"iswifi"];
    [parameters setNotNilObject:@(settings.deny_video) forKey:@"deny_vedio"];
    NSURLRequest* request=[NSMutableURLRequest postRequestWithURL:[NSString stringWithFormat:@"%@/api-user-main/setconfig",HOST] bodyParameters:parameters];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if (response.success&&successHandler) {
            KFDAuxiliaryFunctionSettings* settings=[KFDAuxiliaryFunctionSettings modelObjectFromDictionary:response.data];
            successHandler(settings);
        }else if (failureHander){
            failureHander(response);
        }
    }];
#ifdef NETWORKING_ENABLED
    [task resume];
#endif
    return task;
}

-(NSURLSessionTask*)getMessagesWithMaxCountPerPage:(NSUInteger)maxCount page:(NSUInteger)page successHandler:(KFDGetMessagesSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSMutableDictionary* parameters=[NSMutableDictionary dictionary];
    [parameters setNotNilObject:@(maxCount) forKey:@"ps"];
    [parameters setNotNilObject:@(page) forKey:@"p"];
    NSURLRequest* request=[NSMutableURLRequest getRequestWithURL:[NSString stringWithFormat:@"%@/api-user-msg/list",HOST] parameters:parameters];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if (response.success) {
            if (successHandler) {
                NSMutableArray* messages=[NSMutableArray array];
                for (NSDictionary* item in response.data[@"list"]) {
                    KFDMessageSummary* message=[KFDMessageSummary modelObjectFromDictionary:item];
                    [messages addObject:message];
                }
                successHandler(messages);
            }
        }else if (failureHandler){
            failureHandler(response);
        }
    }];
#ifdef NETWORKING_ENABLED
    [task resume];
#endif
    return task;
}

-(NSURLSessionTask*)checkoutMessageWithId:(NSString *)messageId successHandler:(KFDCheckoutMessageSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSMutableDictionary* parameters=[NSMutableDictionary dictionary];
    [parameters setNotNilObject:messageId forKey:@"id"];
    NSURLRequest* request=[NSMutableURLRequest getRequestWithURL:[NSString stringWithFormat:@"%@/api-user-msg/detail",HOST] parameters:parameters];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if (response.success) {
            if (successHandler) {
                KFDMessage* message=[KFDMessage modelObjectFromDictionary:response.data];
                successHandler(message);
            }
        }else if(failureHandler){
            failureHandler(response);
        }
    }];
    [task resume];
    return task;
}

-(NSURLSessionTask*)getChatsWithSuccessHandler:(KFDGetChatsSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSURLRequest* request=[NSMutableURLRequest getRequestWithURL:[NSString stringWithFormat:@"%@/api-find-vip/pm",HOST] parameters:nil];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if (response.success) {
            NSMutableArray* chats=[NSMutableArray array];
            NSArray* list=response.data[@"list"];
            for (NSDictionary* item in list) {
                KFDChat* chat=[KFDChat modelObjectFromDictionary:item];
                [chats addObject:chat];
            }
            successHandler(chats);
        }else if (failureHandler){
            failureHandler(response);
        }
    }];
    [task resume];
    return task;
}

-(NSURLSessionTask*)getAlarmSettingsWithType:(NSString*)type successHandler:(KFDGetAlarmSettingsSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSMutableDictionary* parameters=[NSMutableDictionary dictionary];
    [parameters setNotNilObject:type forKey:@"typename"];
    NSURLRequest* request=[NSMutableURLRequest getRequestWithURL:[NSString stringWithFormat:@"%@/api-market/warning",HOST] parameters:parameters];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if (response.success) {
            if (successHandler) {
                NSDictionary* config=response.data[@"config"];
                KFDAlarmSettings* settings=[KFDAlarmSettings modelObjectFromDictionary:config];
                successHandler(settings);
            }
        }else if (failureHandler){
            failureHandler(response);
        }
    }];
#ifdef NETWORKING_ENABLED
    [task resume];
#endif
    return task;
}

-(NSURLSessionTask*)updateAlarmSettings:(KFDAlarmSettings *)settings successHandler:(KFDUpdateAlarmSettingsSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSMutableDictionary* parameters=[NSMutableDictionary dictionary];
    [parameters setNotNilObject:settings.typename forKey:@"typename"];
    [parameters setNotNilObject:settings.isfloat?@"1":@"0" forKey:@"isfloat"];
    [parameters setNotNilObject:settings.base_price forKey:@"base_price"];
    [parameters setNotNilObject:settings.float_price forKey:@"float_price"];
    [parameters setNotNilObject:settings.ispoint?@"1":@"0" forKey:@"ispoint"];
    [parameters setNotNilObject:settings.point_max forKey:@"point_max"];
    [parameters setNotNilObject:settings.point_min forKey:@"point_min"];
    NSURLRequest* request=[NSMutableURLRequest postRequestWithURL:[NSString stringWithFormat:@"%@/api-market/dowarning",HOST] bodyParameters:parameters];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if (response.success) {
            if (successHandler) {
                successHandler();
            }
        }else if(failureHandler){
            failureHandler(response);
        }
    }];
#ifdef NETWORKING_ENABLED
    [task resume];
#endif
    return task;
}

-(NSURLSessionTask*)getAlarmRingtoneSettingsWithSuccessHandler:(KFDGetAlarmRingtoneSettingsSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSURLRequest* request=[NSMutableURLRequest getRequestWithURL:[NSString stringWithFormat:@"%@/api-user-main/sound",HOST] parameters:nil];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if (response.success) {
            if (successHandler) {
                KFDAlarmRingtoneSettings* settings=[KFDAlarmRingtoneSettings modelObjectFromDictionary:response.data[@"config"]];
                successHandler(settings);
            }
        }else if (failureHandler){
            failureHandler(response);
        }
    }];
#ifdef NETWORKING_ENABLED
    [task resume];
#endif
    return task;
}

-(NSURLSessionTask*)updateAlarmRingtoneSettings:(KFDAlarmRingtoneSettings *)settings successHandler:(KFDUpdateAlarmRingtoneSettingsSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSMutableDictionary* parameters=[NSMutableDictionary dictionary];
    [parameters setNotNilObject:settings.up_sound?@"2":@"1" forKey:@"up_sound"];
    [parameters setNotNilObject:settings.down_sound?@"2":@"1" forKey:@"down_sound"];
    [parameters setNotNilObject:settings.shock?@"1":@"0" forKey:@"shock"];
    [parameters setNotNilObject:settings.istime?@"1":@"0" forKey:@"istime"];
    [parameters setNotNilObject:settings.stime forKey:@"stime"];
    [parameters setNotNilObject:settings.etime forKey:@"etime"];
    [parameters setNotNilObject:settings.notice_time forKey:@"notice_time"];
    NSURLRequest* request=[NSMutableURLRequest postRequestWithURL:[NSString stringWithFormat:@"%@/api-user-main/dosound",HOST] bodyParameters:parameters];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if (response.success) {
            if (successHandler) {
                successHandler();
            }
        }else if (failureHandler){
            failureHandler(response);
        }
    }];
#ifdef NETWORKING_ENABLED
    [task resume];
#endif
    return task;
}

-(NSURLSessionTask*)getAvatarListWithSuccessHandler:(KFDGetAvatarListSuccessHandler)successHandler failureHandler:(KFDRequestFailureHandler)failureHandler
{
    NSURLRequest* request=[NSMutableURLRequest getRequestWithURL:[NSString stringWithFormat:@"%@/api-user-main/getface",HOST] parameters:nil];
    NSURLSessionTask* task=[NSURLSessionTask dataTaskWithSession:_session request:request completionHandler:^(KFDResponseBody *response) {
        if (response.success) {
            if (successHandler) {
                NSArray* faceList=response.data[@"face"];
                successHandler(faceList);
            }
        }else if(failureHandler){
            failureHandler(response);
        }
    }];
#ifdef NETWORKING_ENABLED
    [task resume];
#endif
    return task;
}

@end
